'use strict'

// 切换到文件所在目录
process.chdir(__dirname)

const titbit = require('titbit')
const fs = require('fs')
const dbcfg = require('./dbconfig.js')
const pg = require('pg')
const wxkey = require('./wxkey.js')
const {httpcli} = require('gohttp')
const token = require('titbit-token')
const tbloader = require('titbit-loader')

try{
    fs.accessSync('./images')
}catch(err){
    fs.mkdirSync('./images')
}

let psql = new pg.Pool(dbcfg);
let cert_path = '/usr/local/share' 

const app = new titbit({
    // 开启调试模式，若错误会输出调试信息
    debug:true,
    cert:`${cert_path}/api.dwx.asia.pem`,
    key:`${cert_path}/api.dwx.asia.key`
})

let tb = new tbloader();
tb.init(app);

app.addService('psql',psql);
app.addService('imagePath',`${__dirname}/images`)

let tok = new token({
    //token有效期，单位为秒
    expires:45,
    //必须是32位字符
    key:'1dwfelgfiwufhomdsfksfsmfsdmf8y6r',
    //必须是16位字符
    iv:'37rt78otg8yfelkg'
})

app.get('/mp-login/:code',async c=>{
    let auth_url = `https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code`
                    +`?appid=${wxkey.appid}`
                    +`&secret=${wxkey.secret}`
                    +`&js_code=${c.param.code}`
                    +`&grant_type=authorization_code`
    
    let ret = await httpcli.get(auth_url)
                            .then(res=>{
                                return res.json()
                            })
    c.send(tok.make(ret))
})

// 运行在1234端口
app.run(1234)